<template>
  <!-- :model="form"  -->
  <el-form ref="form" label-width="100px">
    <el-form-item label="SPU名称">
      <el-input placeholder="请输入SPU名称" size="normal" clearable v-model="spuParams.spuName"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select value-key="" :placeholder="请选择所属品牌" clearable filterable @change="" v-model="spuParams.tmId">
        <el-option v-for="item in allTradeMark" :key="item.id" :label="item.tmName" :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" placeholder="请输入SPU描述" v-model="spuParams.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图标">
      <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handleUpload">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible" style="margin-top: 1%">
        <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select value-key="" :placeholder="unSelectSaleAttr.length
        ? `还未选择${unSelectSaleAttr.length}个`
        : `暂无数据可选择`
        " v-model="saleAttrIdAndValueName" clearable filterable @change="" style="width: 25%">
        <el-option v-for="item in unSelectSaleAttr" :key="item.id" :label="item.name"
          :value="`${item.id}:${item.name}`">
        </el-option>
      </el-select>
      <el-button type="primary" icon="Plus" size="default" style="margin-left: 10px" :disabled="!saleAttrIdAndValueName"
        @click="addSaleAttr">添加属性</el-button>

      <el-table :data="saleAttr" style="width: 100%; margin-top: 20px" border>
        <el-table-column prop="prop" label="序号" type="index" width="80px" align="center"></el-table-column>
        <el-table-column label="销售属性名字" width="200px" prop="saleAttrName"></el-table-column>
        <el-table-column prop="prop" label="销售属性值">
          <template #="{ row, $index }">
            <el-tag v-for="(item, index) in row.spuSaleAttrValueList" :key="row.id" class="mx-1" closable
              style="margin-right: 10px" @close="row.spuSaleAttrValueList.splice(index, 1)">{{ item.saleAttrValueName
              }}</el-tag>
            <el-input placeholder="请你输入属性值" size="small" style="width: 100px; margin-right: 10px" v-if="row.flag"
              v-model="row.saleAttrValue" @blur="toLook(row)"></el-input>
            <el-button @click="toEdit(row)" v-else type="primary" size="small" icon="Plus"></el-button>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作" width="150px">
          <template #="{ row, $index }">
            <el-button type="danger" size="small" icon="Delete" @click="saleAttr.splice($index, 1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button :disabled="saleAttr.length > 0 ? false : true" type="primary" size="default"
        @click="save">保存</el-button>
      <el-button type="default" size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
  import type {
    SpuData,
    AllTradeMark,
    SpuHasImg,
    SaleAttrResponseData,
    HasSaleAttrResponseData,
    Trademark,
    SpuImg,
    SaleAttr,
    HasSaleAttr,
    SaleAttrValue,
  } from "@/api/product/spu/type";

  import {
    reqAllTradeMark,
    reqSpuImageList,
    reqSpuHasSaleAttr,
    reqAllSaleAttr,
    reqAddOrUpdateSpu,
  } from "@/api/product/spu/index";
  import { ref, computed } from "vue";
  import { ElMessage } from "element-plus";

  // 存储已有的SPU这些数据
  let allTradeMark = ref<Trademark[]>([]);
  let imgList = ref<SpuImg[]>([]);
  let saleAttr = ref<SaleAttr[]>([]);
  let allSaleAttr = ref<HasSaleAttr[]>([]);
  let spuParams = ref<SpuData>({
    category3Id: "", // 收集三级分类ID
    spuName: "", // SPU名字
    description: "", // SPU的描述
    tmId: "", // 品牌ID
    spuImageList: [],
    spuSaleAttrList: [],
  });

  let dialogVisible = ref(false);
  let dialogImageUrl = ref("");

  let saleAttrIdAndValueName = ref<string>("");

  let $emit = defineEmits(["changeScene"]);
  // 点击取消按钮：通知父组件切换场景为1，展示已有SPU数据
  const cancel = () => {
    $emit("changeScene", { flag: 0, params: 'update' });
    inintSpuForm()
  };

  // 子组件书写一个方法
  const initHasSpuData = async (spu: SpuData) => {
    // console.log(spu, "-----------------------");
    spuParams.value = spu;
    // 获取全部品牌数据
    const res: AllTradeMark = await reqAllTradeMark();
    // 获取某一个品牌旗下全部售卖商品的图片
    const res1: SpuHasImg = await reqSpuImageList(spu.id as number);
    // 获取已有的SPU销售属性的数据
    const res2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number);
    // 获取整个项目全部SPU的销售属性
    const res3: HasSaleAttrResponseData = await reqAllSaleAttr();

    allTradeMark.value = res.data;
    imgList.value = res1.data.map((item) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      };
    });
    saleAttr.value = res2.data;
    allSaleAttr.value = res3.data;
  };

  const inintSpuForm = () => {
    Object.assign(spuParams.value, {
      category3Id: "", // 收集三级分类ID
      spuName: "", // SPU名字
      description: "", // SPU的描述
      tmId: "", // 品牌ID
      spuImageList: [],
      spuSaleAttrList: [],
    })
    saleAttr.value = []
    imgList.value = []
    saleAttrIdAndValueName.value = ''
  }


  const initAddSpu = async (c3Id: number | string) => {
    console.log('添加spu')
    inintSpuForm()
    spuParams.value.category3Id = c3Id
    // 获取全部品牌数据
    const res: AllTradeMark = await reqAllTradeMark();
    // 获取整个项目全部SPU的销售属性
    const res3: HasSaleAttrResponseData = await reqAllSaleAttr();
    allTradeMark.value = res.data;
    allSaleAttr.value = res3.data;

  }

  const handlePictureCardPreview = (file: any) => {
    dialogVisible.value = true;
    dialogImageUrl.value = file.url;
  };

  const handleRemove = (file: any) => {
    console.log("删除照片");
  };

  const handleUpload = (file: any) => {
    if (
      file.type == "image/png" ||
      file.type == "image/jpeg" ||
      file.type == "/image/gif"
    ) {
      if (file.size / 1024 / 1024 < 3) {
        ElMessage({
          type: "success",
          message: "上传成功",
        });
        return true;
      } else {
        ElMessage({
          type: "error",
          message: "上传文件大小务必小于3M",
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "上传文件格式务必PNG|JPEG|GIF",
      });
      return false;
    }
  };

  const addSaleAttr = () => {
    // baseSaleAttrId: number,
    // saleAttrName: string
    // spuSaleAttrValueList: spuSaleAttrValueList,
    const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(":");
    let newSaleAttr: SaleAttr = {
      baseSaleAttrId,
      saleAttrName,
      spuSaleAttrValueList: [],
    };
    saleAttr.value.push(newSaleAttr);
    saleAttrIdAndValueName.value = "";
  };

  const toEdit = (row: SaleAttr) => {
    row.flag = true;
    row.saleAttrValue = "";
  };

  const toLook = (row: SaleAttr) => {
    const { baseSaleAttrId, saleAttrValue } = row;
    let newSaleAttrValue: SaleAttrValue = {
      baseSaleAttrId,
      saleAttrValueName: saleAttrValue as string,
    };

    if ((saleAttrValue as string).trim() == "") {
      ElMessage({
        type: "error",
        message: "属性值不能为空",
      });
      return;
    }

    let repeat = row.spuSaleAttrValueList.find((item) => {
      return item.saleAttrValueName == saleAttrValue;
    });

    if (repeat) {
      ElMessage({
        type: "error",
        message: "属性值不能重复",
      });
      return;
    }

    row.spuSaleAttrValueList.push(newSaleAttrValue);

    row.saleAttrValue = "";
    row.flag = false;
  };

  let unSelectSaleAttr = computed(() => {
    let unSelectArr = allSaleAttr.value.filter((item) => {
      return saleAttr.value.every((item1) => {
        return item.name != item1.saleAttrName;
      });
    });
    return unSelectArr;
  });

  let save = async () => {
    spuParams.value.spuImageList = imgList.value.map((item: any) => {
      return {
        imgName: item.name,
        imgUrl: (item.response && item.response.data) || item.url,
      };
    });
    // console.log(spuParams.value.spuImageList);
    spuParams.value.spuSaleAttrList = saleAttr.value;
    console.log(spuParams.value);
    let res = await reqAddOrUpdateSpu(spuParams.value);
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: spuParams.value.id ? '更新成功' : '添加成功'
      })
      $emit("changeScene", { flag: 0, params: spuParams.value.id ? 'update' : 'add' });
      inintSpuForm()
    } else {
      ElMessage({
        type: 'error',
        message: spuParams.value.id ? '更新失败' : '添加失败'
      })
    }
  };

  defineExpose({ initHasSpuData, initAddSpu });
</script>

<style scoped></style>
